from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
from bs4 import BeautifulSoup

# 配置Selenium
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

# 指定Chrome驱动路径
service = Service('./chromedriver.exe')  # 替换为你的chromedriver路径

driver = webdriver.Chrome(service=service, options=chrome_options)

# https://quote.eastmoney.com/qihuo/ps2508.html
# https://gushitong.baidu.com/futures/ab-JM2508
try:
    url = "https://finance.sina.com.cn/futures/quotes/SM2605.shtml"
    driver.get(url)

    # 等待页面加载（可根据需要调整等待时间或使用显式等待）
    time.sleep(5)

    # 获取页面源码
    page_source = driver.page_source

    # 使用BeautifulSoup解析
    soup = BeautifulSoup(page_source, 'html.parser')
    # 示例：提取页面标题
    title = soup.text
    print("页面标题:", title)

    with open("fetch/app_sina.html", "w", encoding="utf-8") as file:
        file.write(str(soup))  # 或 file.write(soup.prettify())

    print("HTML 已保存到 app.html")


    # 查找class为"price"的span标签
    price_span = soup.find('span', class_='real-price')

    if price_span:
        # 获取文本内容并转换为浮点数
        price = float(price_span.text)
        print(price)  # 输出: 1311.0
        # 如果需要保留两位小数
        print("{:.2f}".format(price))  # 输出: 1311.00
    else:
        print("未找到价格信息")

finally:
    driver.quit()